//
//  HYCDestinationController.m
//  FamilyTravel
//
//  Created by dllo on 15/10/21.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "HYCDestinationController.h"

#import "HYCHeadDocument.h"


#pragma mark 目的地界面
#define SWIDTH [UIScreen mainScreen].bounds.size.width
#define SHEIGHT [UIScreen mainScreen].bounds.size.height
#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height
@interface HYCDestinationController ()<UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate>
@property(nonatomic, retain) UITableView *tableView;
@property(nonatomic, retain) NSMutableArray *arr;
@property(nonatomic, retain) NSMutableArray *collArr;
@property(nonatomic, retain) UICollectionView *collectionView;
@property(nonatomic, retain) MBProgressHUD *hud;
@property(nonatomic, retain) UIView *headView;
@property(nonatomic, retain) NSMutableDictionary *dicId;
@end

@implementation HYCDestinationController

- (void)dealloc {
    [_arr release];
    [_tableView release];
    [_collectionView release];
    [_collArr release];
    [_headView release];
    [_hud release];
    [_dicId release];
    
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //    self.view.backgroundColor = [UIColor redColor];
    
    UIImage *beanTripBackgroundImage=[UIImage imageNamed:@"tou.jpg"];
    [self.navigationController.navigationBar setBackgroundImage:beanTripBackgroundImage forBarMetrics:UIBarMetricsDefault];
    
    
    self.title = @"目的地";
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 110) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [_tableView release];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    //横岗去掉
    self.tableView.separatorStyle = NO;
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(WIDTH / 5.36, HEIGHT / 7.5);
    flowLayout.minimumInteritemSpacing = 10;
    flowLayout.minimumLineSpacing = 10;
    flowLayout.sectionInset = UIEdgeInsetsMake(40, 20, 10, 20);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 100) collectionViewLayout:flowLayout];
    //    self.tableView.tableHeaderView = self.collectionView;
    self.tableView.tableFooterView = self.collectionView;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.pagingEnabled = NO;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerClass:[HYCCollHeaderCell class] forCellWithReuseIdentifier:@"reuse"];
    
    UILabel *label =[[UILabel alloc] initWithFrame:CGRectMake(SWIDTH / (SWIDTH / 110), 3, 110, 25)];
    [self.collectionView addSubview:label];
    label.text = @"其他热门国家";
    label.textAlignment = NSTextAlignmentCenter;
    [label release];
    
    //头部
    self.headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT / 4.446)];
    self.tableView.tableHeaderView = self.headView;
    
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.labelText = @"加载中...";
    
    
    NSArray *arr = @[@"亚洲", @"欧洲", @"北美洲", @"南美洲", @"大洋洲", @"非洲", @"南极洲"];
    
    for (NSInteger i = 0; i < 2; i++) {
        for (NSInteger j = 0; j < 4; j++) {
            if ((i + 1) * (j + 1) > 6) {
                break;
            } else {
                UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
                button.frame = CGRectMake(15 + WIDTH / 4.16 * j, 5 + HEIGHT / 8.33 * i, WIDTH / 5, HEIGHT / 11.11);
                [self.headView addSubview:button];
                NSString *imageName = [NSString stringWithFormat:@"%d.png", (4 * i + j)];
                [button setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
                [button addTarget:self action:@selector(changeAction:) forControlEvents:UIControlEventTouchUpInside];
                [button setTitle:arr[4 * i + j] forState:UIControlStateNormal];
                [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                button.tag = 1000 + 4 * i + j;
            }
            
        }
    }
    
    
    
//    [self createData];
    
    [self netWorkingJudge];
    
}



- (void)netWorkingJudge {
    
    AFNetworkReachabilityManager *judge = [AFNetworkReachabilityManager sharedManager];
    [judge  startMonitoring];
    [judge setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        if (status == 1 || status == 2) {
            
            NSString *strURl = @"http://open.qyer.com/qyer/footprint/continent_list?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&page=1&track_app_channel=App%2520Store&track_app_version=6.7&track_device_info=iPhone%25204%28ChinaMobile%2CChinaUnicom%29&track_deviceid=AB5B28ED-8670-4190-873A-F09EFE3EB3E8&track_os=ios%25207.1.2&v=1";
            NSURL *url = [NSURL URLWithString:strURl];
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
            [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
                //
                self.arr = [NSMutableArray array];
                
                for (NSDictionary *tempDic in dic[@"data"][0][@"hot_country"]) {
                    if (![tempDic[@"flag"] isEqualToNumber:@2]) {
                        
                        HYCDestinationModel  *movie = [[HYCDestinationModel alloc] init];
                        [movie setValuesForKeysWithDictionary:tempDic];
                        [self.arr addObject:movie];
                        [movie release];
                    }
                }
                // 上面的coll;
                self.collArr = [NSMutableArray array];
                
                
                for (NSDictionary *tempDic in dic[@"data"][0][@"country"]) {
                    if (![tempDic[@"flag"] isEqualToNumber:@2]) {
                        
                        
                        HYCDesCollHeaderModel *movie = [[HYCDesCollHeaderModel alloc] init];
                        [movie setValuesForKeysWithDictionary:tempDic];
                        [self.collArr addObject:movie];
                        [movie release];
                        
                    }
                }
                
                [self.hud removeFromSuperview];
                [self.tableView reloadData];
                [self.collectionView reloadData];
            }];
            
            
            
            
        }else {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"没有网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            
            [alertView show];
        }
        
        
    }];
    
}

// 点击不同洲切换不同地方
- (void)changeAction:(UIButton *)button{
    
    for (NSInteger i = 0; i < 7; i++) {
        if (button.tag == 1000 + i) {
            
            //            button.backgroundColor = [UIColor redColor];
            
            NSString *strURl = @"http://open.qyer.com/qyer/footprint/continent_list?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&page=1&track_app_channel=App%2520Store&track_app_version=6.7&track_device_info=iPhone%25204%28ChinaMobile%2CChinaUnicom%29&track_deviceid=AB5B28ED-8670-4190-873A-F09EFE3EB3E8&track_os=ios%25207.1.2&v=1";
            NSURL *url = [NSURL URLWithString:strURl];
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
            [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
                self.arr = [NSMutableArray array];
                for (NSDictionary *tempDic in dic[@"data"][i][@"hot_country"]) {
                    HYCDestinationModel  *movie = [[HYCDestinationModel alloc] init];
                    [movie setValuesForKeysWithDictionary:tempDic];
                    [self.arr addObject:movie];
                    [movie release];
                }
                // 上面的coll;
                self.collArr = [NSMutableArray array];
                
                for (NSDictionary *tempDic in dic[@"data"][i][@"country"]) {
                    if (![tempDic[@"flag"] isEqualToNumber:@2]) {
                        HYCDesCollHeaderModel *model = [[HYCDesCollHeaderModel alloc] init];
                        [model setValuesForKeysWithDictionary:tempDic];
                        [self.collArr addObject:model];
                    }
                    
                }
                
                [self.tableView reloadData];
                [self.collectionView reloadData];
            }];
            
            
        }
    }
    
}


//- (void)createData {
//    
//}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.collArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HYCCollHeaderCell *collCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    collCell.countryLabel.text = [self.collArr[indexPath.row] cnname];
    
    
    [collCell.countryImageView sd_setImageWithURL:[NSURL URLWithString:[self.collArr[indexPath.row] photo]]placeholderImage:[UIImage imageNamed:@"zw.png"]];
    
    // cell动画
    collCell.layer.shadowColor = [[UIColor blackColor]CGColor];
    collCell.alpha = 0;
    [UIView beginAnimations:@"rotation" context:NULL];
    [UIView setAnimationDuration:1];
    collCell.alpha = 1;
    [UIView commitAnimations];
    
    
    self.collectionView.frame = CGRectMake(0, 0, WIDTH, self.collectionView.contentSize.height);
    [self.tableView setTableFooterView:self.collectionView];
    return collCell;
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    HYCSecondPushdisController *sPDVC = [[HYCSecondPushdisController alloc] init];
    sPDVC.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:sPDVC animated:YES];
    
    sPDVC.model = self.collArr[indexPath.row];
    
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HYCSecondPushdisController *sPDVC = [[HYCSecondPushdisController alloc] init];
    sPDVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:sPDVC animated:YES];
    
    sPDVC.model = self.arr[indexPath.row];
    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.arr.count;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return HEIGHT / 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *reuse = @"reuse";
    HYCDestinationCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[[HYCDestinationCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse] autorelease];
    }
    HYCDestinationModel *model = self.arr[indexPath.row];
    cell.model = model;
    
    
    // cell动画
    cell.layer.shadowColor = [[UIColor blackColor]CGColor];
    cell.alpha = 1;
    [UIView beginAnimations:@"rotation" context:NULL];
    [UIView setAnimationDuration:1];
    cell.alpha = 2;
    [UIView commitAnimations];
    
    
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
